<template>
  <Dialog
    :title="dialogTitle"
    v-model="dialogVisible"
    style="min-width: 1200px"
    scroll
    max-height="600"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="110px"
      v-loading="formLoading"
    >
      <!-- 合同编号下拉框（优化：初始加载200条+过滤功能） -->
      <el-form-item label="合同编号" prop="contractNo">
        <el-select
          v-model="formData.contractNo"
          filterable
          placeholder="请选择合同编号"
          :filter-method="handleContractFilter"
          v-loading="contractLoading"
        >
          <el-option
            v-for="item in filteredContractList"
            :key="item.contractNo"
            :label="item.contractNo"
            :value="item.contractNo"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="合同名称" prop="contractName">
        <el-input v-model="formData.contractName" disabled placeholder="系统自动获取" />
      </el-form-item>
      <el-form-item label="合同乙方名称" prop="supplierName">
        <el-input v-model="formData.supplierName" disabled placeholder="系统自动获取" />
      </el-form-item>
      <el-form-item label="付款备注" prop="paymentRemark">
        <el-input v-model="formData.paymentRemark" placeholder="请输入付款备注" />
      </el-form-item>
      <ContentWrap>
        <el-form-item prop="detailSaveReqVOS" style="display: none" />
        <el-table :data="formData.detailSaveReqVOS" :stripe="true">
          <el-table-column label="序号" type="index" width="60" />
          <el-table-column label="付款计划编号" align="center" prop="planNo" width="290">
            <template #default="{ row }">
              <el-input v-model="row.planNo" placeholder="系统自动生成" disabled class="!w-260px" />
            </template>
          </el-table-column>
          <el-table-column label="付款期数" align="center" prop="period" width="80">
            <template #default="{ row }">
              <el-input v-model="row.period" type="number" class="!w-55px" />
            </template>
          </el-table-column>
          <el-table-column label="计划付款金额" align="center" prop="planPaymentAmount" width="130">
            <template #default="{ row }">
              <el-input v-model="row.planPaymentAmount" disabled type="number" class="!w-100px" />
            </template>
          </el-table-column>
          <el-table-column label="计划付款日期" align="center" prop="planDate" width="170">
            <template #default="{ row }">
              <el-date-picker
                v-model="row.planDate"
                value-format="YYYY-MM-DD"
                placeholder="计划付款日期"
                class="!w-140px"
              />
            </template>
          </el-table-column>
          <el-table-column label="付款类型" align="center" prop="paymentType" width="130">
            <template #default="{ row }">
              <el-select
                v-model="row.paymentType"
                placeholder="选择付款类型"
                clearable
                class="!w-100px"
              >
                <el-option
                  v-for="dict in getStrDictOptions(DICT_TYPE.PAYMENT_TYPE)"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="计划付款比例" align="center" prop="planPaymentRatio" width="160">
            <template #default="{ row }">
              <el-input
                v-model="row.planPaymentRatio"
                type="number"
                class="!w-120px"
                @change="calculatePaymentAmount(row)"
              >
                <template #append>%</template>
              </el-input>
            </template>
          </el-table-column>
          <el-table-column
            label="实际付款状态"
            align="center"
            prop="actualPaymentStatus"
            width="170"
          >
            <template #default="{ row }">
              <el-select
                v-model="row.actualPaymentStatus"
                placeholder="实际付款状态"
                clearable
                class="!w-140px"
              >
                <el-option
                  v-for="dict in getStrDictOptions(DICT_TYPE.ACTUAL_PAYMENT_STATUS)"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="实际付款金额" align="center" prop="actualAmount" width="130">
            <template #default="{ row }">
              <el-input v-model="row.actualAmount" type="number" class="!w-100px" />
            </template>
          </el-table-column>
          <el-table-column label="实际付款日期" align="center" prop="actualDate" width="170">
            <template #default="{ row }">
              <el-date-picker
                v-model="row.actualDate"
                value-format="YYYY-MM-DD"
                placeholder="实际付款日期"
                class="!w-140px"
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" fixed="right" align="center" min-width="120px">
            <template #default="scope">
              <el-button
                link
                type="danger"
                @click="handleDelete(scope.$index)"
                v-hasPermi="['erp:contract-payment-plan:delete']"
                :disabled="formData.detailSaveReqVOS.length <= 1"
              >
                删除此条
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </ContentWrap>
      <div style="text-align: center">
        <el-button @click="addDetailSaveReqVOS">
          <Icon icon="ep:plus" class="mr-5px" />添加一行
        </el-button></div
      >
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { getStrDictOptions, DICT_TYPE } from '@/utils/dict'
import { ContractPaymentPlanApi, ContractPaymentPlanVO } from '@/api/erp/contractpaymentplan'
import { ContractApi, ContractVO } from '@/api/erp/contract'
import { formatDate } from '@/utils/formatTime.js'
import { ElMessage } from 'element-plus'

/** 合同付款计划 表单 */
defineOptions({ name: 'ContractPaymentPlanForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

// -------------------------- 合同下拉框优化（初始加载200条+过滤） --------------------------
const allContractList = ref<ContractVO[]>([]) // 全量合同列表（缓存）
const filteredContractList = ref<ContractVO[]>([]) // 过滤后的合同列表
const contractLoading = ref(false) // 合同列表加载状态
const PAGE_SIZE = 200 // 初始加载数量限制

/** 加载所有合同（全量缓存，仅加载一次） */
const loadAllContracts = async () => {
  if (allContractList.value.length > 0) return allContractList.value

  contractLoading.value = true
  try {
    const data = await ContractApi.getContractqueryAll()
    allContractList.value = data.list || []
    return allContractList.value
  } catch (error) {
    ElMessage.error('加载合同列表失败，请重试')
    allContractList.value = []
    return []
  } finally {
    contractLoading.value = false
  }
}

/** 合同过滤方法（初始显示200条，搜索时全量过滤） */
const handleContractFilter = async (query?: string) => {
  const allContracts = await loadAllContracts()

  // 1. 无搜索时只显示前200条
  if (!query) {
    const baseList = allContracts.slice(0, PAGE_SIZE)
    // 确保已选项在列表中
    const selectedContract = formData.value.contractNo
    if (selectedContract && !baseList.some((item) => item.contractNo === selectedContract)) {
      const originalContract = allContracts.find((item) => item.contractNo === selectedContract)
      if (originalContract) {
        filteredContractList.value = [originalContract, ...baseList].slice(0, PAGE_SIZE + 1)
        return
      }
    }
    filteredContractList.value = baseList
    return
  }

  // 2. 有搜索时全量过滤
  const lowerQuery = query.toLowerCase()
  let results = allContracts.filter(
    (item) =>
      item.contractNo.toLowerCase().includes(lowerQuery) ||
      (item.contractName && item.contractName.toLowerCase().includes(lowerQuery))
  )

  // 确保已选项在结果中
  const selectedContract = formData.value.contractNo
  if (selectedContract && !results.some((item) => item.contractNo === selectedContract)) {
    const originalContract = allContracts.find((item) => item.contractNo === selectedContract)
    if (originalContract) {
      results.unshift(originalContract)
    }
  }

  filteredContractList.value = results
}
// ----------------------------------------------------------------------------

// 表单基础状态
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formLoading = ref(false)
const formType = ref('')

// 生成临时ID用于临时标识
const generateTempId = () => {
  return 'temp_' + Math.random().toString(36).substr(2, 9)
}

/** 创建空的明细行 */
const createEmptyDetail = () => {
  return {
    id: generateTempId(),
    paymentPlanId: undefined,
    planNo: undefined,
    period: undefined,
    planDate: undefined,
    paymentType: undefined,
    planPaymentRatio: undefined,
    planPaymentAmount: undefined,
    actualPaymentStatus: undefined,
    actualAmount: undefined,
    actualDate: undefined
  }
}
// 表单数据
const formData = ref({
  id: undefined,
  planNo: undefined,
  contractId: undefined,
  contractNo: undefined,
  contractName: undefined,
  supplierName: undefined,
  paymentRemark: undefined,
  detailSaveReqVOS: [createEmptyDetail()]
})

// 合同总金额（用于计算付款金额）
const contractAmountInclTax = ref(0)

// 表单校验规则
const formRules = reactive({
  contractNo: [{ required: true, message: '合同编号不能为空', trigger: 'change' }],
  contractName: [{ required: true, message: '合同名称不能为空', trigger: 'blur' }],
  supplierName: [{ required: true, message: '合同乙方名称不能为空', trigger: 'blur' }],
  detailSaveReqVOS: [
    {
      type: 'array',
      required: true,
      message: '至少需要一条付款计划',
      trigger: 'change'
    },
    {
      validator: (rule: any, value: any[], callback: any) => {
        const errors: string[] = []
        value.forEach((item, index) => {
          if (!item.period) errors.push(`第${index + 1}行：付款期数不能为空`)
          if (!item.planDate) errors.push(`第${index + 1}行：计划付款日期不能为空`)
          if (!item.actualPaymentStatus) errors.push(`第${index + 1}行：实际付款状态不能为空`)
          if (!item.paymentType) errors.push(`第${index + 1}行：付款类型不能为空`)
          if (
            item.planPaymentAmount === undefined ||
            item.planPaymentAmount === null ||
            isNaN(Number(item.planPaymentAmount))
          ) {
            errors.push(`第${index + 1}行：请输入有效的计划付款金额`)
          }
        })

        if (errors.length > 0) {
          callback(new Error(errors.join('；')))
          callback(message.error(errors.join('；')))
        } else {
          callback()
        }
      },
      trigger: 'change'
    }
  ]
})

const formRef = ref() // 表单 Ref

/** 监听合同编号变化，同步合同信息 */
watch(
  () => formData.value.contractNo,
  async (newVal) => {
    if (!newVal) {
      formData.value.contractId = undefined
      formData.value.contractName = undefined
      formData.value.supplierName = undefined
      contractAmountInclTax.value = 0
      return
    }

    // 从全量列表中匹配合同信息
    const allContracts = await loadAllContracts()
    const matchedContract = allContracts.find((item) => item.contractNo === newVal)

    if (matchedContract) {
      formData.value.contractId = matchedContract.id
      formData.value.contractName = matchedContract.contractName || ''
      formData.value.supplierName = matchedContract.partyB || ''
      contractAmountInclTax.value = matchedContract.contractAmountInclTax || 0

      // 重新计算所有明细的金额
      formData.value.detailSaveReqVOS.forEach((row) => {
        calculatePaymentAmount(row)
      })
    } else {
      // 未找到匹配的合同
      formData.value.contractName = ''
      formData.value.supplierName = ''
      contractAmountInclTax.value = 0
    }
  },
  { immediate: true }
)

/** 根据比例计算计划付款金额 */
const calculatePaymentAmount = (row: any) => {
  // 边界值处理：确保总金额和比例有效
  if (
    !contractAmountInclTax.value ||
    !row.planPaymentRatio ||
    isNaN(Number(row.planPaymentRatio))
  ) {
    row.planPaymentAmount = undefined
    return
  }

  // 计算并保留两位小数
  row.planPaymentAmount = Number(
    ((contractAmountInclTax.value * row.planPaymentRatio) / 100).toFixed(2)
  )
}

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()

  // 初始加载合同列表（前200条）
  await handleContractFilter()

  // 修改时加载数据
  if (id) {
    formLoading.value = true
    try {
      const res = await ContractPaymentPlanApi.getContractPaymentPlan(id)
      formData.value = { ...res }

      // 处理明细数据，转换日期格式
      formData.value.detailSaveReqVOS = res.detailRespVOS?.map((item: any) => ({
        ...item,
        actualDate: item.actualDate ? formatDate(item.actualDate, 'YYYY-MM-DD') : '',
        planDate: item.planDate ? formatDate(item.planDate, 'YYYY-MM-DD') : ''
      })) || [createEmptyDetail()]

      delete formData.value.detailRespVOS
    } catch (error) {
      ElMessage.error('加载表单数据失败，请重试')
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open })

/** 添加一行明细 */
const addDetailSaveReqVOS = () => {
  formData.value.detailSaveReqVOS.push(createEmptyDetail())
  formRef.value?.validateField('detailSaveReqVOS')
}

/** 删除一行明细 */
const handleDelete = (index: number) => {
  if (formData.value.detailSaveReqVOS.length <= 1) {
    message.warning('至少保留一条付款计划')
    return
  }
  formData.value.detailSaveReqVOS.splice(index, 1)
  formRef.value?.validateField('detailSaveReqVOS')
}

/** 提交表单 */
const emit = defineEmits(['success'])
const submitForm = async () => {
  if (!formRef.value) return

  // 表单校验
  await formRef.value.validate()

  formLoading.value = true
  try {
    const data = formData.value as unknown as ContractPaymentPlanVO

    // 处理明细数据：移除临时ID并转换日期
    data.detailSaveReqVOS = data.detailSaveReqVOS.map((item: any) => {
      const { id, actualDate, planDate, ...rest } = item
      const processedItem = {
        ...rest,
        ...(actualDate && { actualDate: new Date(actualDate).getTime() }),
        ...(planDate && { planDate: new Date(planDate).getTime() })
      }

      // 保留非临时ID
      if (!String(id).startsWith('temp_')) {
        processedItem.id = id
      }

      return processedItem
    })

    // 提交请求
    if (formType.value === 'create') {
      await ContractPaymentPlanApi.createContractPaymentPlan(data)
      message.success(t('common.createSuccess'))
    } else {
      await ContractPaymentPlanApi.updateContractPaymentPlan(data)
      message.success(t('common.updateSuccess'))
    }

    dialogVisible.value = false
    emit('success')
  } catch (error: any) {
    ElMessage.error(error.message || '操作失败，请重试')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    planNo: undefined,
    contractId: undefined,
    contractNo: undefined,
    contractName: undefined,
    supplierName: undefined,
    paymentRemark: undefined,
    detailSaveReqVOS: [createEmptyDetail()]
  }
  formRef.value?.resetFields()
  contractAmountInclTax.value = 0
}
</script>